<template>
	<div class="">
		<div ref="amapRef" class="w-full h-full"></div>
		<div class="absolute top-[79px] left-[25px] z-9999 w-[360px]">
			<el-input
				placeholder="请输入搜索内容，ENTER键搜索"
				id="tipinput"
				prefix-icon="Search"
				v-model="keywords"
				@keyup.enter.native="searchKeyWord"
			></el-input>
			<div class="max-h-[200px] overflow-y-auto add-box">
				<div v-for="item in address" @click="handleSearch(item)" :key="item" class="truncate add-item" :title="item.name">{{ item.name }}</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { useScript } from '/@/hooks/web/useScript';
import axios from 'axios';

const emits = defineEmits(['select']);
const keywords = ref();
const props = defineProps({
	latitude: {
		type: Number,
		default: 0,
	},
	longitude: {
		type: Number,
		default: 0,
	},
});
const address: any = ref([]);
const A_MAP_URL = 'https://webapi.amap.com/maps?v=1.4.15&key=24a6afd6ab0b81c1bda89e736ff24c6f&plugin=AMap.Autocomplete,AMap.PlaceSearch';
const amapRef = ref();
const { toPromise } = useScript({ src: A_MAP_URL });
let map: any;
let AMap: any;
let marker: any;
async function initMap() {
	await toPromise();
	await nextTick();
	const wrapEl = unref(amapRef);
	if (!wrapEl) return;
	AMap = (window as any).AMap;
	map = new AMap.Map(wrapEl, {
		resizeEnable: true,
	});
	if (props.latitude && props.longitude) {
		const ct = new AMap.LngLat(props.longitude, props.latitude);
		map.setZoomAndCenter(14, ct);
	}
	marker = new AMap.Marker({
		clickable: true,
		position: [props.longitude, props.latitude],
	});
	marker.setMap(map);
	map.on('click', function (arg: any) {
		if (arg.lnglat.lng && arg.lnglat.lat) {
			const pos = [arg.lnglat.lng, arg.lnglat.lat];
			marker.setPosition(pos);
			emits('select', pos);
		}
	});
}
function searchKeyWord() {
	axios.get('https://restapi.amap.com/v3/place/text?key=24a6afd6ab0b81c1bda89e736ff24c6f&keywords=' + keywords.value).then((res) => {
		console.log(res);
		if (res.data.status === '1') {
			address.value = res.data.pois;
		} else {
			address.value = [];
		}
	});
}
const handleSearch = (item: any) => {
	const loc = item.location.split(',');
	const ct = new AMap.LngLat(loc[0], loc[1]);
	map.setCenter(ct);
	marker.setPosition(ct);
	const pos = [ct.lng, ct.lat];
	emits('select', pos);
};
onMounted(() => {
	initMap();
});
</script>

<style lang="scss" scoped>
:deep(.amap-marker-label) {
	color: #000;
	background: #00e400;
	border: unset;
	border-radius: 4px;
}
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}
.add-box {
	border-radius: 4px;
	background-color: rgba($color: #fff, $alpha: 0.9);
	margin-top: 2px;
	box-shadow: var(--el-box-shadow-light);
	.add-item {
		padding: 4px 8px;
		cursor: pointer;
		&:hover {
			color: #2e5cf6;
		}
	}
}
</style>
